package com.fintech.pangu.autoconfigure.actuate.metrics;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.util.StringUtils;

import java.net.InetAddress;

/**
 * 实现系统级别的 Common Tags
 */
public class CommonTagsMeterRegistryCustomizer implements MeterRegistryCustomizer {

    @Autowired
    private InetUtils inetUtils;

    @Value("${spring.application.name}")
    private String applicationName;


    @Override
    public void customize(MeterRegistry registry) {
        Tags tags = Tags.empty();

        // 应用名
        if(StringUtils.hasText(applicationName)){
            tags = tags.and(Tag.of("application.name", applicationName));
        }

        // hostname
        /*String hostname = "";
        InetUtils.HostInfo hostInfo = inetUtils.findFirstNonLoopbackHostInfo();
        if(hostInfo != null){
            hostname = hostInfo.getHostname();
        }
        if(StringUtils.hasText(hostname)){
            tags = tags.and(Tag.of("hostname", hostname));
        }*/

        // IP
        String ip = "";
        InetAddress inetAddress = inetUtils.findFirstNonLoopbackAddress();
        if(inetAddress != null){
            ip = inetAddress.getHostAddress();
        }
        if(StringUtils.hasText(ip)){
            tags = tags.and(Tag.of("ip", ip));
        }


        // 设置commonTags
        registry.config().commonTags(tags);
    }
}
